#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <time.h>
#include "formsetget.h"
#include "formpantilt.h"



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    DriverFile = 0;
    ui->LineEditFileName->setText(DEFAULT_DRIVER_NAME);
    ui->LineEditOutputFile->setText(QApplication::applicationDirPath() + "/" + DEFAULT_FILE_NAME);
}

MainWindow::~MainWindow()
{
    if (DriverFile > 0)
        DriverFile = ::close(DriverFile);
    delete ui;
}

void MainWindow::on_PushButtonOpen_clicked()
{
    DriverFile = open(ui->LineEditFileName->text().toUtf8(), 0);
    if (DriverFile > 0)
    {
        enableButtons();
    }
}

void MainWindow::on_PushButtonClose_clicked()
{
    DriverFile = ::close(DriverFile);
    if (DriverFile <= 0)
    {
        disableButtons();
    }
}

void MainWindow::enableButtons()
{
    ui->LabelStatus->setText("Ouvert");
    ui->PushButtonClose->setEnabled(true);
    ui->PushButtonOpen->setEnabled(false);
    ui->PushButtonSetGet->setEnabled(true);
    ui->PushButtonStreamOn->setEnabled(true);
    ui->PushButtonStreamOff->setEnabled(true);
    ui->PushButtonGrab->setEnabled(true);
    ui->PushButtonRead->setEnabled(true);
    ui->PushButtonTakePic->setEnabled(true);
    ui->PushButtonPanTilt->setEnabled(true);
}

void MainWindow::disableButtons()
{
    ui->LabelStatus->setText("Ferme");
    ui->PushButtonClose->setEnabled(false);
    ui->PushButtonOpen->setEnabled(true);
    ui->PushButtonSetGet->setEnabled(false);
    ui->PushButtonStreamOn->setEnabled(false);
    ui->PushButtonStreamOff->setEnabled(false);
    ui->PushButtonGrab->setEnabled(false);
    ui->PushButtonRead->setEnabled(false);
    ui->PushButtonTakePic->setEnabled(false);
    ui->PushButtonPanTilt->setEnabled(false);
}

void MainWindow::on_pushButtonQuit_clicked()
{
    close();
}

void MainWindow::on_PushButtonStreamOn_clicked()
{
    //int retval;
    //long outputValue;
    //retval = 0;
    //retval =
    ioctl(DriverFile, IOCTL_STREAMON);//, &outputValue);
}

void MainWindow::on_PushButtonStreamOff_clicked()
{
    //int retval;
    //long outputValue;
    //retval = 0;
    //retval =
    ioctl(DriverFile, IOCTL_STREAMOFF);//, &outputValue);
}

void MainWindow::on_PushButtonGrab_clicked()
{
    //int retval;
    //long outputValue;
    //retval = 0;
    //retval=
    ioctl(DriverFile, IOCTL_GRAB);
    //do something...
}

void MainWindow::on_PushButtonRead_clicked()
{
    FILE *foutput;
    unsigned char * inBuffer;
    unsigned char * finalBuf;
	int result = 0;
	int mySize = 0;
	int dataFromUser = 0;

    inBuffer = (unsigned char*) malloc((42666)* sizeof(unsigned char));
    finalBuf = (unsigned char*) malloc((42666 * 2)* sizeof(unsigned char));
	if((inBuffer == NULL) || (finalBuf == NULL)){
//		return -1;
	}

    //foutput = fopen("/home/emperador/ele784-usb-cam/test.jpg", "wb");
    //fopen(ui->LineEditOutputFile->text().toUtf8(), "wb");

	if(foutput != NULL){

		result = ioctl(DriverFile, IOCTL_STREAMON);

//		result = ioctl(DriverFile, IOCTL_GRAB);

		mySize = read(DriverFile, inBuffer, dataFromUser);
		printf("READ = %i\n", mySize);

		if (mySize<0){
			printf("Failed to READ\n");
			free(inBuffer);
			free(finalBuf);
//		    waitsec(3);
//		    return 0;
		}

		result = ioctl(DriverFile, IOCTL_STREAMOFF);

            memcpy (finalBuf, inBuffer, HEADERFRAME1);
            memcpy (finalBuf + HEADERFRAME1, dht_data, DHT_SIZE);
            memcpy (finalBuf + HEADERFRAME1 + DHT_SIZE,
		inBuffer + HEADERFRAME1,
		(mySize - HEADERFRAME1));

		fwrite (finalBuf, mySize + DHT_SIZE, 1, foutput);

            fclose(foutput);
        }
	free(inBuffer);
	free(finalBuf);
 //   waitsec(1);
    
}

void MainWindow::on_PushButtonTakePic_clicked()
{
    FILE *foutput;
    unsigned char * inBuffer;
    unsigned char * finalBuf;
	int result = 0;
	int mySize = 0;
	int dataFromUser = 0;

    inBuffer = (unsigned char*) malloc((42666)* sizeof(unsigned char));
    finalBuf = (unsigned char*) malloc((42666 * 2)* sizeof(unsigned char));
	if((inBuffer == NULL) || (finalBuf == NULL)){
//		return -1;
	}

	foutput = fopen("/home/emperador/ele784-usb-cam/test.jpg", "wb");

	if(foutput != NULL){

		result = ioctl(DriverFile, IOCTL_STREAMON);

		result = ioctl(DriverFile, IOCTL_GRAB);

		mySize = read(DriverFile, inBuffer, dataFromUser);
		printf("READ = %i\n", mySize);

		if (mySize<0){
			printf("Failed to READ\n");
			free(inBuffer);
			free(finalBuf);
//		    waitsec(3);
//		    return 0;
		}

		result = ioctl(DriverFile, IOCTL_STREAMOFF);

            memcpy (finalBuf, inBuffer, HEADERFRAME1);
            memcpy (finalBuf + HEADERFRAME1, dht_data, DHT_SIZE);
            memcpy (finalBuf + HEADERFRAME1 + DHT_SIZE,
		inBuffer + HEADERFRAME1,
		(mySize - HEADERFRAME1));

		fwrite (finalBuf, mySize + DHT_SIZE, 1, foutput);

            fclose(foutput);
        }
	free(inBuffer);
	free(finalBuf);
 //   waitsec(1);
}

void MainWindow::waitSec(unsigned int sec)
{
        clock_t endwait;
        endwait = clock () + sec*CLOCKS_PER_SEC ;
        while (clock() < endwait) {}
}

void MainWindow::on_PushButtonSetGet_clicked()
{
    //DialogSetGet SetGetWindow;
    //SetGetWindow.show();
    FormSetGet* SetGetWindow = new FormSetGet(this);
    SetGetWindow->setFile(DriverFile);
    SetGetWindow->show();
}

void MainWindow::on_PushButtonPanTilt_clicked()
{
    //create dialog for pan + tilt
    FormPanTilt* PanTiltWindow = new FormPanTilt(this);
    PanTiltWindow->setFileHandle(DriverFile);
    PanTiltWindow->show();
}

void MainWindow::displayPic()
{
    int result;
    QString tmpStr;
    QImage imageObject;
    tmpStr = ui->LineEditOutputFile->text();
    //tmpStr = "/home/dude/QT/CamTest/test.bmp";
    result = imageObject.load(tmpStr);
    ui->ImageDisplay->setPixmap(QPixmap::fromImage(imageObject));
    if (result <= 0)
        ui->LabelError->setText("Erreur ! Incapable de charger le fichier '" + tmpStr + "' ...");
    else
        ui->LabelError->setText("Succes !!! Fichier charge : " + tmpStr);
}

void MainWindow::on_PushButtonLoadFile_clicked()
{
    displayPic();
}
